package com.example.springbootdemo.demos.web;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
 
public class NIOReadFileExample {
    public static void main(String[] args) {
        // 创建通道，使用 try-with-resources 语句自动关闭资源
        try (FileInputStream inputStream = new FileInputStream("C:\\Users\\Administrator\\Desktop\\demo.txt");
             FileChannel inChannel = inputStream.getChannel()) {
             // 创建一个缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            // 使用 while 循环读取文件中的所有数据
            while (inChannel.read(byteBuffer) != -1) {
                // 切换到读模式
                byteBuffer.flip();
                // 读取缓冲区中的数据
                byte[] bytes = new byte[byteBuffer.limit()];
                byteBuffer.get(bytes);
                System.out.println(new String(bytes));
                // 清空缓冲区
                byteBuffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}